﻿#include "keyboardlistenthread.h"

#include <QDebug>
#include "kbd_types.h"
#include "get_key.h"

KeyboardListenThread::KeyboardListenThread(QObject *parent)
    : QThread(parent)
{
    kbd_init();
}

KeyboardListenThread::~KeyboardListenThread()
{
    stop();
    quit();
    wait();
    kbd_close();
}

void KeyboardListenThread::stop()
{
    qDebug() << "KeyboardListenThread Thread stop: " << QThread::currentThreadId();
    QMutexLocker locker(&m_lock);
    isStop = true;
}

void KeyboardListenThread::run()
{
    qDebug() << "KeyboardListenThread Thread stop: " << QThread::currentThreadId();
    char key;
    while(!isStop)
    {
        key = get_key();
        switch(key){
        case MWKEY_KP_DEL:
            emit deletePressed();
            break;
        case MWKEY_KP_MULTIPLY:
            emit asteriskPressed();
            break;
        case MWKEY_KP_ENTER:
            emit enterPressed();
            break;
        case MWKEY_END:
            emit escPressed();
            break;
        case MWKEY_KP_PLUS:
            emit plusPressed();
            break;
        default:
            qDebug() << key << "Pressed";
        }
        msleep(50);

        // 检测是否停止
        {
            QMutexLocker locker(&m_lock);
            if (isStop)
                break;
        }
        // locker超出范围并释放互斥锁
    }
}



